<template>
  <u-popup
    :show="showCommentPopup"
    :height="650"
    mode="bottom"
    @close="popupClose"
  >
    <view class="form-wrapper">
      <u--form
        :model="form"
        ref="dataForm"
        :rules="rules"
        labelPosition="left"
        labelWidth="0"
        :labelStyle="{ color: '#333', fontWeight: '500', fontSize: '28rpx' }"
        class="form-inner"
      >
        <u-form-item prop="title" :borderBottom="false">
          <view class="form-section">
            <view class="section-label">
              <text class="label-text">标题</text>
              <text class="required-mark">*</text>
            </view>
            <u--input
              v-if="!isReplyMode"
              v-model="form.title"
              placeholder="标题内容尽量意思完整"
              class="form-input"
            />
          </view>
        </u-form-item>
        <u-form-item prop="zhu_ti" :borderBottom="false">
          <view class="form-section">
            <view class="section-label">
              <text class="label-text">主题</text>
              <text class="required-mark">*</text>
            </view>
            <u-checkbox-group v-model="form.zhu_ti" placement="row">
              <view class="checkbox-grid">
                <u-checkbox
                  v-for="(item, index) in state.SysLabelList"
                  :key="index"
                  :label="item.name"
                  :name="item.id"
                  shape="circle"
                  activeColor="#4A90E2"
                  inactiveColor="#eee"
                  class="checkbox-item"
                  :iconSize="24"
                  :labelStyle="{ fontSize: '26rpx', marginLeft: '12rpx' }"
                />
              </view>
            </u-checkbox-group>
          </view>
        </u-form-item>
        <u-form-item prop="content" :borderBottom="false">
          <view class="form-section">
            <view class="section-label">
              <text class="label-text">正文</text>
              <text class="required-mark">*</text>
            </view>
            <u--textarea
              v-model="form.content"
              placeholder="请输入正文(不能上传任何形式的联系方式)"
              placeholderClass="placeholder-style"
              inputClass="input-style"
            />
          </view>
        </u-form-item>
        <u-form-item prop="img" :borderBottom="false">
          <view class="form-section">
            <view class="section-label">
              <text class="label-text">图片上传</text>
              <!-- <text class="required-mark">*</text> -->
            </view>
            <u-upload
              :fileList="form.img"
              @afterRead="onChooseAvatarZiZhi"
              @delete="handleDeleteZiZhi"
              name="unlimitedUpload"
              multiple
              :maxCount="5"
              accept="image"
            >
              <template #default>
                <view
                  v-if="form.img.length != 5"
                  style="
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    margin: 10px;
                    justify-content: center;
                  "
                >
                  <u-icon name="plus" size="40"></u-icon>
                  <text>点击上传</text>
                </view>
              </template>
            </u-upload>
          </view>
        </u-form-item>
      </u--form>
      <!-- 3.5 提交按钮（优化渐变+hover效果+加载状态） -->
      <view class="submit-section">
        <u-button
          type="primary"
          text="确定提交"
          @click="submitForm"
          shape="circle"
          size="large"
          :customStyle="{
            width: '100%',
            height: '90rpx',
            borderRadius: '45rpx',
            fontSize: '32rpx',
            fontWeight: '500',
            background: 'linear-gradient(135deg, #4A90E2 0%, #357ABD 100%)',
            border: 'none',
            marginTop: '20rpx',
            boxShadow: '0 8rpx 24rpx rgba(74, 144, 226, 0.3)',
            transition: 'all 0.3s ease',
          }"
          :loading="isSubmitting"
          loadingColor="#fff"
          class="submit-btn"
        />
      </view>
    </view>
  </u-popup>
</template>
<script setup>
import { reactive, toRefs, onMounted, computed, watch, ref } from "vue";
import { GetIndexZhuTi, PostLiuYanSave } from "@/api/news.js";
import {
  showToast,
  showLoading,
  hideLoading,
  showModalNoCancel,
  showModal,
} from "@/utils/toast";
const emit = defineEmits(["UpClose"]);
const props = defineProps({
  showCommentPopup: {
    type: Boolean,
    default: false,
  },
});
const state = reactive({
  SysLabelList: [],
  form: {
    title: "",
    zhu_ti: [],
    content: "",
    img: [],
  },
  rules: {
    title: [{ required: true, message: "请输入标题", trigger: "blur" }],
    zhu_ti: [
      {
        required: true,
        type: "array",
        min: 1,
        message: "请至少选择一个主题",
        trigger: ["change"],
      },
    ],
    content: [{ required: true, message: "请输入正文", trigger: "blur" }],
  },
});
const { form, rules } = toRefs(state);
const init = async () => {
  try {
    const res = await GetIndexZhuTi();
    state.SysLabelList = res.data;
  } catch (error) {}
};
init();

const dataForm = ref(null);
const submitForm = async () => {
  const valid = await dataForm.value.validate();
  if (!valid) return;
  try {
    showLoading("提交中...");
    const res = await PostLiuYanSave(state.form);
    hideLoading();
    if (res.code == 10000) {
      showModal(
        {
          title: "系统消息",
          content: "留言已发送，审核通过后方可查看",
          showCancel: false, // 隐藏取消按钮
        },
        (result) => {
          if (result.error) {
            uni.showToast({ title: "通知显示失败", icon: "none" });
            return;
          }
          emit("UpClose");
          //   uni.navigateBack({
          //     delta: 1,
          //   });
        }
      );
    }
  } catch (error) {}
};
const popupClose = async () => {
  emit("UpClose");
};
const handleDeleteZiZhi = (event) => {
  form.value.img.splice(event.index, 1);
};
const onChooseAvatarZiZhi = (e) => {
  try {
    // 获取选择的文件（u-upload的e.file是单个文件对象，无需[0]）
    const file = e.file;

    if (!file || !file[0].url) {
      showToast("未获取到图片，请重新选择");
      return;
    }

    // 直接调用uni.uploadFile，使用回调处理结果
    uni.uploadFile({
      url: `${import.meta.env.VITE_API_URL}/upload/image`,
      filePath: file[0].url,
      name: "file",
      header: {
        Authorization: "Bearer " + uni.getStorageSync("token"),
        "content-type": "multipart/form-data; charset=utf-8",
      },
      formData: {
        type: "avatar",
        file_type: "7",
      },
      // 上传成功的回调
      success: (res) => {
        try {
          const data = JSON.parse(res.data);
          if (data.code == 10000 && data.data?.url) {
            // 上传成功，添加到图片列表
            form.value.img.push({
              url: data.data.web_url,
              web_url: data.data.url,
            });
            showToast("图片上传成功");
          } else {
            showToast(data.msg || "上传失败");
          }
        } catch (parseErr) {
          showToast("上传结果解析失败");
        }
      },
      // 上传失败的回调
      fail: (err) => {
        showToast("网络错误，上传失败");
        console.error("上传失败:", err);
      },
    });
  } catch (err) {
    showToast("处理图片时出错，请重试");
  }
};
</script>
<style lang="scss" scoped>
.title-view {
  background-color: #f7f7f7;
  // background-color: red !important;
  .title-input {
    padding-left: 10px;
    background: #fff;
    margin: 5px 10px;
    padding: 5px;
    border-radius: 2px;
  }
}
.checkbox-grid {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16rpx 20rpx;
}

/* 3. 表单容器（增强卡片感） */
.form-wrapper {
  background: white;
  border-radius: 24rpx;
  padding: 0rpx 30rpx;
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.08);
  position: relative;
  z-index: 2;
  .form-inner {
    width: 100%;
  }
  /*  表单 section 通用样式 */
  .form-section {
    margin-bottom: 50rpx;
    width: 100%;
    position: relative;

    &:last-child {
      margin-bottom: 10rpx;
    }

    // 标签样式（带必填星号）
    .section-label {
      display: flex;
      align-items: center;
      margin-bottom: 16rpx;

      .label-text {
        font-size: 28rpx;
        font-weight: 500;
        color: #333;
      }

      .required-mark {
        color: #ff4d4f;
        margin-left: 8rpx;
        font-size: 28rpx;
      }
    }

    // 提示文本样式
    .hint-text {
      display: block;
      margin-top: 12rpx;
      font-size: 24rpx;
      color: #666;
      line-height: 1.5;
      padding-left: 4rpx;
      animation: fadeIn 0.3s ease;
    }
  }
}
</style>
